package cn.test.activemq.normal.quene;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;

import javax.jms.*;

public class QueueReciverWithRedelivery {
	public static void main(String[] args) {
		ConnectionFactory connectionFactory;
		// Connection ：JMS 客户端到JMS Provider 的连接  
		ActiveMQConnection connection = null;
		// Session： 一个发送或接收消息的线程  
		Session session;
		// Destination ：消息的目的地;消息发送给谁.  
		Destination destination;
		// 消费者，消息接收者
		MessageConsumer consumer;
		connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.1.159:61616");
		try {
			// 构造从工厂得到连接对象  
			connection = (ActiveMQConnection) connectionFactory.createConnection();
			// 启动  
			connection.start();

			RedeliveryPolicy queuePolicy = new RedeliveryPolicy();
			queuePolicy.setInitialRedeliveryDelay(0);
			queuePolicy.setRedeliveryDelay(1000);
			queuePolicy.setUseExponentialBackOff(false);
			queuePolicy.setMaximumRedeliveries(2);

			RedeliveryPolicy topicPolicy = new RedeliveryPolicy();
			topicPolicy.setInitialRedeliveryDelay(0);
			topicPolicy.setRedeliveryDelay(1000);
			topicPolicy.setUseExponentialBackOff(false);
			topicPolicy.setMaximumRedeliveries(3);

			// Receive a message with the JMS API
			RedeliveryPolicyMap map = connection.getRedeliveryPolicyMap();
			map.put(new ActiveMQTopic(">"), topicPolicy);
			map.put(new ActiveMQQueue(">"), queuePolicy);
			// 获取操作连接  
			//这个最好还是有事务
			//auto的确认模式，出错，继续发送7次，都发到该listener，spring下是直接确认了，报错也确认
			//client收到一次，但是都不确认，spring下的配置会确认，出错继续7此发送，最后删除或者到死信队列
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			// 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置  
			destination = session.createQueue("test-queue");
			consumer = session.createConsumer(destination);
			consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message message) {
					try {
						System.out.println(message);
						if (null != message) {
							System.out.println("收到消息");
						}

						if(((TextMessage)message).getText().equals("eee")){
							throw new RuntimeException("eeeee");
						}
					} catch (JMSException e) {
						System.out.println("...");
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
